package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsRole;
import com.qf.service.PermsService;
import com.qf.service.RoleService;
import com.qf.util.JacksonUtil;
import com.qf.util.Permission;
import com.qf.util.PermissionUtil;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import com.qf.vo.PermVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/admin/role")
public class RoleController {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermsService permsService;


    @GetMapping("/options")
    public Object options(){
        List<DtsRole> roleList=roleService.findAllRoles();
        List<CatVo> catVoList = roleList.stream().map(dtsRole -> {
            CatVo vo = new CatVo();
            vo.setValue(dtsRole.getId());
            vo.setLabel(dtsRole.getName());
            return vo;
        }).collect(Collectors.toList());

        return ResponseUtil.ok(catVoList);
    }

    @RequiresPermissions(value = "admin:role:list")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "查询")
    @GetMapping("/list")
    public Object list(
            String rolename,
            String sort,
            String order,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit
    ){
        IPage<DtsRole> ipage = roleService.findRolePageByQuery(rolename,sort,order,page,limit);
        Map data = new HashMap<>();
        data.put("total",ipage.getTotal());
        data.put("items",ipage.getRecords());
        return ResponseUtil.ok(data);
    }

    @GetMapping("/permissions")
    public Object permissions(Integer roleId){

        String basePackage="com.qf.controller";
        List<Permission> permissions=PermissionUtil.listPermission(applicationContext,basePackage);
        List<PermVo> systemPermissions = PermissionUtil.listPermVo(permissions);


        Integer[] roleIds={roleId};
        Set<String> assignedPermissions = permsService.findPermsByRoleIds(roleIds);

        //可能是*
        assignedPermissions = handlerPerms(assignedPermissions,basePackage);

        Map data=new HashMap();
        data.put("systemPermissions",systemPermissions);
        data.put("assignedPermissions",assignedPermissions);

        return ResponseUtil.ok(data);
    }

    @RequiresPermissions(value = "admin:role:permissions")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "授权")
    @PostMapping("/permissions")
    public Object permissions(@RequestBody String json){
        Integer roleId = JacksonUtil.parseInteger(json, "roleId");
        List<String> permissions = JacksonUtil.parseStringList(json, "permissions");

        permsService.updatePermListByRoleId(roleId,permissions);


        return ResponseUtil.ok();
    }

    @RequiresPermissions(value = "admin:role:create")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody DtsRole dtsRole){
        dtsRole.setAddTime(new Date());
        dtsRole.setDeleted(false);
        dtsRole.setEnabled(true);
        dtsRole.setUpdateTime(new Date());
        roleService.insertRole(dtsRole);
        return ResponseUtil.ok();

    }

    //http://localhost:8080/admin/role/delete
    @RequiresPermissions(value = "admin:role:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsRole dtsRole){
        dtsRole.setDeleted(true);
        roleService.deleteRole(dtsRole);
        return ResponseUtil.ok();
    }

    @RequiresPermissions(value = "admin:role:update")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsRole dtsRole){
        dtsRole.setUpdateTime(new Date());
        roleService.updateRole(dtsRole);
        return ResponseUtil.ok();
    }






    private Set<String> handlerPerms(Set<String> assignedPermissions,String basePackage) {
        //判断是不是*
        /*if (CollectionUtils.isEmpty(assignedPermissions)){
            return new HashSet<>();
        }*/

        Optional.ofNullable(assignedPermissions).orElse(new HashSet<>());

        if (assignedPermissions.contains("*")) {
            //超级管理员
            List<Permission> permissionList = PermissionUtil.listPermission(applicationContext, basePackage);
            permissionList.forEach(System.out::println);
            return permissionList.stream().map(permission -> permission.getRequiresPermissions().value()[0]
            ).collect(Collectors.toSet());

        }else {
            //不是超级管理员
            return assignedPermissions;
        }

    }


}
